﻿
namespace BLPicker.OnTheFly.Tools.Common
{
    using System;
    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Reflection;
    using Microsoft.CSharp;

    [Serializable]
    public class SourceCodeCompiler
    {

        public Assembly DynamicCompile(string sourceCode, string compiledAssemblyName, IEnumerable<string> referencedAssemblies, bool generateExecutable, bool generateInMemory, out StringCollection output)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(sourceCode));

            CompilerParameters compilerParameters = new CompilerParameters(referencedAssemblies.ToArray(), compiledAssemblyName, false)
            {
                GenerateExecutable = generateExecutable,
                GenerateInMemory = generateInMemory
            };

            using (CSharpCodeProvider provider = new CSharpCodeProvider())
            {

                CompilerResults compilerResults = provider.CompileAssemblyFromSource(
                    compilerParameters,
                    sourceCode);

                output = compilerResults.Output;

                return !compilerResults.Errors.HasErrors
                    ? compilerResults.CompiledAssembly
                    : null;
            }
        }

    }
}
